
package com.joysuch.wwyt.dataperm.spring.listeners;

import cn.zlg.common.datadump.annotation.DataDumpEntity;
import cn.zlg.common.datadump.service.DataDumpService;
import com.joysuch.wwyt.dataperm.spring.ClassScanListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 数据导入、导出权限注解扫描监听器
 *
 */
@Component
public class DataDumpAnnotationClassScanListener implements ClassScanListener {

    private static final Logger logger = LoggerFactory.getLogger(DataDumpAnnotationClassScanListener.class);

    @Autowired
    private DataDumpService dataDumpService;

    @Override
    public void onScanClass(Class clazz) {
        if (hasAnnotation(clazz, DataDumpEntity.class)) {
            scanForDataPermFields(clazz);
        }
    }

    private boolean hasAnnotation(Class clazz, Class... annotations) {
        for (Class a : annotations) {
            if (clazz.getAnnotation(a) != null) {
                return true;
            }
        }
        return false;
    }

    private void scanForDataPermFields(Class clazz) {
        DataDumpEntity annotation = (DataDumpEntity) clazz.getAnnotation(DataDumpEntity.class);
        try {
            // 校验注解是否正确
            dataDumpService.validate(clazz);
            dataDumpService.register(clazz, annotation);
            logger.info("导入、导出注册：{}, {} ", annotation.name(), clazz.getName());
        } catch (Exception e) {
            logger.warn("检测失败: 导入导出: 类{}，{}", clazz.getName(), e.getMessage());
            throw new RuntimeException(String.format("导入导出: 类%s检测失败，请检查配置", clazz.getName()), e);
        }
    }

}
